<template>
  <div>
    <Row class="y_query_right">
      <Button type="error" icon="md-trash" :disabled="!hasSelectedProducts" @click="safeDelete()" class="y_condition">删除</Button>
    </Row>
    <Row class="y_query_right">
      <Cascader class="y_condition" :data="categoryTree" @on-change="changeCategory" change-on-select clearable style="width: 300px; max-width: 300px; text-align: left;"></Cascader>
      <Input type="text" v-model="searchParams.code" placeholder="产品SKU" clearable class="y_condition"></Input>
      <Input type="text" v-model="searchParams.name" placeholder="产品名称" clearable class="y_condition"></Input>
      <Select v-model="searchParams.usedType" class="y_condition" style="text-align: left;" clearable>
        <Option v-for="(item, index) in usedTypes" :key="index" :value="item.value">{{item.label}}</Option>
      </Select>
      <Button type="primary" icon="md-search" @click="query()" class="y_condition">查询</Button>
    </Row>
    <Divider size="small"></Divider>

    <div style="text-align: left; padding-left: 25px; margin-bottom: 5px;">
      <Checkbox v-model="selectedAll" :indeterminate="selectedPart" @on-change="changeSelectedAll" :disabled="!hasProducts">全选</Checkbox>
    </div>
    <List border class="data-list">
      <template v-if="!hasProducts">
        <ListItem>
          <div style="width: 100%; text-align: center; color: #ccc;">
            暂无数据
          </div>
        </ListItem>
      </template>
      <template v-else>
        <CheckboxGroup v-model="selectedSKUList">
          <ListItem v-for="(item, index) in productList" :key="index" class="list-item">
            <Row style="width: 100%;">
              <i-col :span="3" :xxl="3" :xl="4" :lg="5" :md="6" :sm="9" :xs="12" style="text-align: left; line-height: 100%;">
                <div class="item-checkbox">
                  <Checkbox :label="item.code"><span></span></Checkbox>
                </div>
                <div class="item-img">
                  <img :src="getProductImg(item)" style="max-width: 100%;"/>
                </div>
              </i-col>
              <i-col :span="21" :xxl="21" :xl="20" :lg="19" :md="18" :sm="15" :xs="12" style="padding-left: 0.5rem;">
                <div class="item-content">
                  <div>
                    <KeyValueView title="SKU">{{item.code}}</KeyValueView>
                    <KeyValueView title="名称">{{item.name}}</KeyValueView>
                  </div>
                  <div>
                    <KeyValueView title="状态" :value="getProductState(item)"></KeyValueView>
                    <KeyValueView title="不可删除" :value="getProductUsedType(item)"></KeyValueView>
                  </div>
                </div>
                <div class="item-bottom">
                  <Button size="small" type="error" icon="md-trash" @click="deleteProduct(item)">删除</Button>
                </div>
              </i-col>
            </Row>
          </ListItem>
        </CheckboxGroup>
      </template>
    </List>

    <!-- 分页 -->
    <div style="margin-top: 20px; text-align: right;">
      <Page :total="page.total" :page-size="page.pageSize" :current="page.pageNum"
            @on-change="changePageNum" @on-page-size-change="changePageSize" :page-size-opts="page.options"
            show-sizer show-elevator show-total/>
    </div>
  </div>
</template>

<script>
import KeyValueView from "../widgets/KeyValueView";
import {createCategoryList, getProductCommonData, isNotEmpty} from "../js/commonUtils";
export default {
  name: "ProductDelete",
  components: {KeyValueView},
  data() {
    return {
      yunKey: this.$store.getters.imgPrefix,
      searchParams: {
        code: "",
        name: "",
        usedType: null,
        categoryId: "",
        categoryLevel: null,
      },
      usedTypes: [
        {label: "未使用", value: 0},
        {label: "已加入购物车", value: 1},
        {label: "已下过单", value: 2},
      ],
      page: {
        total: 0,
        pageNum: 1,
        pageSize: 40,
        options: [40, 60, 80, 120],
      },
      productList: [],
      selectedAll: false,
      selectedPart: false,
      selectedSKUList: [],
      categoryTree: [],

    }
  },
  computed: {
    hasProducts() {
      return this.productList.length > 0;
    },
    hasSelectedProducts() {
      return this.selectedSKUList.length > 0;
    },
  },
  methods: {
    initPageInfo() {
      this.searchParams.code = "";
      this.searchParams.name = "";
      this.searchParams.usedType = null;
      this.searchParams.categoryId = "";
      this.searchParams.categoryLevel = null;
      this.productList.splice(0);
      this.selectedSKUList.splice(0);
      this.selectedAll = false;
      this.selectedPart = false;
    },
    changeCategory(value, selectedData) {
      if(selectedData.length > 0) {
        this.searchParams.categoryId = selectedData[selectedData.length-1].value;
        this.searchParams.categoryLevel = selectedData[selectedData.length-1].level;
      }else{
        this.searchParams.categoryId = "";
        this.searchParams.categoryLevel = null;
      }
    },
    changeSelectedAll(selectedAll) {
      if(selectedAll) {
        this.selectedSKUList.splice(0);
        let selectedCodes = this.productList.map(item => {return item.code});
        this.selectedSKUList.push(...selectedCodes);
      }else{
        this.selectedSKUList.splice(0);
      }
    },
    query() {
      this.$Spin.show();
      let params = this.searchParams;
      params.pageNum = this.page.pageNum;
      params.pageSize = this.page.pageSize;
      this.$apiProduct.queryDeletableProducts(params).then(response => {
        this.$Spin.hide();
        this.productList.splice(0);
        this.selectedSKUList.splice(0);
        if(response.success) {
          let page = response.result;
          this.productList.push(...page.list);
          this.page.total = page.total;
        }else{
          console.error(response);
          this.$Message.error({content: "查询可删除产品失败"+response.errorMessage, duration: 3});
        }
      }).catch(err => {
        this.$Spin.hide();
        this.productList.splice(0);
        console.error(err);
        this.$Message.error({content: "查询可删除产品失败", duration: 3});
      });
    },
    changePageNum(pageNum) {
      this.page.pageNum = pageNum;
      this.query();
    },
    changePageSize(pageSize) {
      this.page.pageNum = 1;
      this.page.pageSize = pageSize;
      this.query();
    },
    getProductImg(item) {
      if(isNotEmpty(item.showImg)) {
        return this.yunKey + item.showImg;
      }
      return "";
    },
    getProductState(item) {
      switch (item.state) {
        case -2:
          return "回收站";
        case -1:
          return "已下架";
        case 0:
          return "已上架";
        case 3:
          return "新建";
      }
      return "";
    },
    getProductUsedType(item) {
      switch (item.usedType) {
        case 0:
          return "";
        case 1:
          return "已加入购物车";
        case 2:
          return "已下过单";
      }
      return "";
    },
    deleteProduct(item) {
      this.selectedSKUList.splice(0, this.selectedSKUList.length, item.code);
      this.safeDelete();
    },
    safeDelete() {
      let self = this;
      this.$Modal.confirm({
        title: "确认",
        content: "确定要删除吗？",
        onOk() {
          self.$Spin.show();
          let params = {
            codes: self.selectedSKUList
          };
          self.$apiProduct.safeDelete(params).then(response => {
            self.$Spin.hide();
            if(response.success) {
              if(response.result == 0) {
                self.$Message.success(response.errorMessage);
              }else{
                self.$Message.success("删除完成");
              }
              self.query();
            }else{
              console.error(response);
              self.$Message.error({content: "删除失败:"+response.errorMessage, duration: 3});
            }
          }).catch(err => {
            self.$Spin.hide();
            console.error(err);
            self.$Message.error({content: "删除失败", duration: 3});
          });
        }
      });
    },
  },
  watch: {
    "selectedSKUList": {
      handler(newVal, oldVal) {
        if(newVal.length > 0) {
          if(newVal.length == this.productList.length) {//全部选中
            this.selectedAll = true;
            this.selectedPart = false;
          }else{
            this.selectedAll = false;
            this.selectedPart = true;
          }
        }else{
          this.selectedAll = false;
          this.selectedPart = false;
        }
      }
    }
  },
  mounted() {
    this.initPageInfo();
    getProductCommonData(this, this.categoryTree, [3], true, createCategoryList);
  }
}
</script>

<style scoped lang="less">
@import (once,optional) "../css/base";

.data-list {
  margin: 1rem 0rem;
  line-height: 25px;
  .list-item {
    .flex-colum-wrap;
    justify-items: left;
    align-items: start;
    .item-checkbox {
      display: inline-block;
      width: 25px;
      height: 25px;
      text-align: center;
      vertical-align: top;
    }
    .item-img {
      width: 130px;
      text-align: center;
      display: inline-block;
    }
    .item-top{
      width: 100%;
      margin-bottom: 5px;
      .flex-row-wrap;
      justify-content: space-between;
    }
    .item-content {
      margin-bottom: 35px;
      text-align: left;
    }
    .item-bottom{
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      display: block;
      //padding: 0 1rem 0.5rem 0;
      cursor: pointer;
      text-align: right;
      button {
        margin-left: 0.5rem;
      }
    }
  }
}
</style>
